<template>
  <div class="content-wrapper">
    <!-- 数据看板 -->
    <div class="dashboard-container">
      <div class="equal-height-row">
        <!-- 左半区 数据统计与图表 -->
        <div class="data-panel">
          <!-- 数据统计卡片 -->
          <div class="stats-grid">
            <div
                v-for="(stat, index) in statistics"
                :key="index"
                class="stat-item"
                :style="{ backgroundColor: stat.color }"
            >
              <i :class="stat.icon"></i>
              <div class="stat-text">
                <div class="value">{{ stat.value }}</div>
                <div class="label">{{ stat.label }}</div>
              </div>
            </div>
          </div>

          <!-- 项目总览条形统计图 -->
          <div class="chart-container">
            <div class="chart-box" ref="barChart"></div>
          </div>
        </div>

        <!-- 右半区 时间轴项目动态 -->
        <div class="timeline-panel">
          <div class="timeline-header">
            <h3>项目动态时间轴</h3>
            <el-button type="primary" icon="el-icon-refresh" @click="fetchTimeline">刷新动态</el-button>
          </div>
          <div class="timeline-container">
            <el-timeline>
              <el-timeline-item
                  v-for="(item, index) in timelineItems"
                  :key="index"
                  :timestamp="item.timestamp"
                  placement="top"
              >
                <div class="timeline-card">
                  <h4>{{ item.title }} <el-tag :type="item.tagType" class="project-tag" size="small">{{ item.tag }}</el-tag></h4>
                  <p>{{ item.content }}</p>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted,nextTick } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import axios from 'axios';

// 创建axios实例
const api = axios.create({
  // 环境变量的基础地址 + 固定的 /api 路径
  baseURL: `${import.meta.env.VITE_API_BASE_URL}`,
  timeout: 10000
});

// 数据统计卡片
const statistics = ref([]);

// 时间轴项目动态
const timelineItems = ref([]);

// 图表引用
const barChart = ref(null);

const checkContentLength = () => {
  nextTick(() => {
    const statItems = document.querySelectorAll('.stat-item');
    statItems.forEach(item => {
      const valueEl = item.querySelector('.value');
      const labelEl = item.querySelector('.label');

      if (valueEl && labelEl) {
        const valueText = valueEl.textContent || '';
        const labelText = labelEl.textContent || '';

        // 移除之前的属性
        item.removeAttribute('data-long-value');
        item.removeAttribute('data-very-long-value');
        item.removeAttribute('data-long-label');
        item.removeAttribute('data-very-long-label');

        // 根据内容长度设置属性
        if (valueText.length > 8) {
          item.setAttribute('data-very-long-value', 'true');
        } else if (valueText.length > 5) {
          item.setAttribute('data-long-value', 'true');
        }

        if (labelText.length > 6) {
          item.setAttribute('data-very-long-label', 'true');
        } else if (labelText.length > 4) {
          item.setAttribute('data-long-label', 'true');
        }
      }
    });
  });
};

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const response = await api.get('/api/dashboard/statistics');
    statistics.value = response.data.map(stat => ({
      ...stat,
      color: getColorByLabel(stat.label)
    }));
    checkContentLength();
  } catch (error) {
    console.error('获取统计数据失败:', error);
    ElMessage.error('获取统计数据失败');
  }
};

// 获取时间轴数据
const fetchTimeline = async () => {
  try {
    const response = await api.get('/api/dashboard/timeline');
    timelineItems.value = response.data;
  } catch (error) {
    console.error('获取时间轴数据失败:', error);
    ElMessage.error('获取时间轴数据失败');
  }
};

// 获取图表数据
const fetchChartData = async () => {
  try {
    const response = await api.get('/api/dashboard/industry-stats');
    initCharts(response.data);
  } catch (error) {
    console.error('获取图表数据失败:', error);
    ElMessage.error('获取图表数据失败');
  }
};

// 根据标签获取颜色
const getColorByLabel = (label) => {
  const colorMap = {
    '在谈项目数': '#f0f7ff',
    '签约金额': '#fff7f0',
    '已落地项目': '#f8fff0',
    '重点跟进企业': '#fff0f8',
    '新项目申报': '#f0f0ff',
    '项目完成率': '#f0fff0',
    '年度目标完成数': '#f8f0ff',
    '客户满意度': '#fff0f0'
  };
  return colorMap[label] || '#f0f7ff';
};

// 初始化图表
const initCharts = (chartData) => {
  // 定义固定的产业类型顺序
  const fixedCategories = [
    '制造业', '信息技术', '金融业', '教育培训', '医疗健康',
    '零售业', '物流运输', '建筑工程', '餐饮服务', '文化娱乐',
    '房地产', '能源环保', '农业', '旅游酒店', '媒体广告',
    '咨询服务', '其他行业'
  ];

  // 按固定顺序重新组织数据
  const orderedData = {
    categories: fixedCategories,
    negotiation: fixedCategories.map(cat => {
      const index = chartData.categories.indexOf(cat);
      return index !== -1 ? chartData.negotiation[index] : 0;
    }),
    signed: fixedCategories.map(cat => {
      const index = chartData.categories.indexOf(cat);
      return index !== -1 ? chartData.signed[index] : 0;
    }),
    landed: fixedCategories.map(cat => {
      const index = chartData.categories.indexOf(cat);
      return index !== -1 ? chartData.landed[index] : 0;
    })
  };

  console.log('前端收到的图表数据:', chartData);

  if (barChart.value) {
    const barChartInstance = echarts.init(barChart.value);

    console.log('传递给ECharts的数据:', {
      categories: chartData.categories,
      negotiation: chartData.negotiation,
      signed: chartData.signed,
      landed: chartData.landed
    });

    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['在谈项目', '签约项目', '落地项目']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '18%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: orderedData.categories,
        axisLabel: {
          interval: 0,
          rotate: 45,
          margin: 15,
          textStyle: {
            fontSize: 10
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '项目数量（个）'
      },
      series: [
        {
          name: '在谈项目',
          type: 'bar',
          stack: 'total',
          emphasis: {
            focus: 'series'
          },
          data: orderedData.negotiation,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          }
        },
        {
          name: '签约项目',
          type: 'bar',
          stack: 'total',
          emphasis: {
            focus: 'series'
          },
          data: orderedData.signed,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#25c98f' },
              { offset: 0.5, color: '#1a9f70' },
              { offset: 1, color: '#1a9f70' }
            ])
          }
        },
        {
          name: '落地项目',
          type: 'bar',
          stack: 'total',
          emphasis: {
            focus: 'series'
          },
          data: orderedData.landed,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#ffd572' },
              { offset: 0.5, color: '#f5a623' },
              { offset: 1, color: '#f5a623' }
            ])
          }
        }
      ]
    };
    barChartInstance.setOption(option);

    // 响应窗口大小变化
    window.addEventListener('resize', () => {
      barChartInstance.resize();
    });
  }
};

// 生命周期钩子
onMounted(() => {
  fetchStatistics();
  fetchTimeline();
  fetchChartData();

  window.addEventListener('resize', checkContentLength);
});
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Microsoft YaHei', sans-serif;
  background-color: #f5f7fa;
  color: #333;
  line-height: 1.6;
  padding-top: 20px;
}

.content-wrapper {
  max-width: 1400px;
  margin: 0 auto;
  padding: 15px 20px 20px;
}

.equal-height-row {
  display: flex;
  gap: 20px;
}

.data-panel, .timeline-panel {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  flex: 1;
}

.data-panel:hover, .timeline-panel:hover {
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  transform: translateY(-3px);
}

/* 更新为固定位置的flex布局 */
.stats-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 25px;
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 8px;
  transition: all 0.3s ease;
  flex: 1 1 calc(25% - 15px); /* 每个卡片占据25%宽度减去间距 */
  min-width: 200px; /* 设置最小宽度防止过度压缩 */
  min-height: 80px; /* 设置固定高度 */
}

.stat-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.08);
}

.stat-item i {
  font-size: 2.2rem;
  margin-right: 15px;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  flex-shrink: 0; /* 防止图标被压缩 */
}

.stat-text {
  flex: 1;
  min-width: 0; /* 允许文本截断 */
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-text .value {
  font-size: 1.6rem;
  font-weight: bold;
  margin-bottom: 5px;
  white-space: nowrap; /* 防止换行 */
  overflow: hidden;
  text-overflow: ellipsis; /* 超出显示省略号 */
  transition: font-size 0.3s ease; /* 添加过渡效果 */
}

.stat-text .label {
  font-size: 0.95rem;
  color: #666;
  white-space: nowrap; /* 防止换行 */
  overflow: hidden;
  text-overflow: ellipsis; /* 超出显示省略号 */
  transition: font-size 0.3s ease; /* 添加过渡效果 */
}

/* 自适应字体大小 */
.stat-item[data-long-value="true"] .value {
  font-size: 1.4rem; /* 长内容时缩小字体 */
}

.stat-item[data-long-label="true"] .label {
  font-size: 0.85rem; /* 长标签时缩小字体 */
}

/* 特别长的内容 */
.stat-item[data-very-long-value="true"] .value {
  font-size: 1.2rem;
}

.stat-item[data-very-long-label="true"] .label {
  font-size: 0.75rem;
}

.chart-container {
  margin-top: 20px;
  height: 380px;
  background: #fff;
  border-radius: 8px;
  padding: 15px;
}

.chart-box {
  height: 100%;
  width: 100%;
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.timeline-header h3 {
  font-size: 1.4rem;
  color: #1a1a1a;
  margin: 0;
}

.timeline-container {
  height: 500px;
  overflow-y: auto;
  padding-right: 10px;
}

.timeline-card {
  border-left: 3px solid #409EFF;
  padding: 15px 20px;
  background: #f8f9fe;
  border-radius: 0 8px 8px 0;
  transition: all 0.3s ease;
}

.timeline-card:hover {
  background: #e6f7ff;
  transform: translateX(5px);
}

.timeline-card h4 {
  font-size: 1.1rem;
  margin-bottom: 10px;
  color: #1a1a1a;
}

.timeline-card p {
  color: #666;
  font-size: 0.95rem;
  line-height: 1.5;
}

.project-tag {
  margin-left: 10px;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .stat-item {
    flex: 1 1 calc(25% - 15px); /* 中等屏幕保持4列 */
  }

  .chart-container {
    height: 420px; /* 在中等屏幕上增加更多高度 */
  }
}

@media (max-width: 992px) {
  .equal-height-row {
    flex-direction: column;
  }

  .data-panel, .timeline-panel {
    width: 100%;
    margin-bottom: 20px;
  }

  .stat-item {
    flex: 1 1 calc(25% - 15px); /* 在992px以下保持4列 */
  }

  .chart-container {
    height: 380px;
  }
}

@media (max-width: 768px) {
  .stat-item {
    flex: 1 1 calc(50% - 15px); /* 小屏幕显示2列 */
  }

  .content-wrapper {
    padding: 10px 15px 15px;
  }

  .chart-container {
    height: 400px; /* 在小屏幕上增加高度 */
  }
}

@media (max-width: 480px) {
  .stat-item {
    flex: 1 1 100%; /* 超小屏幕显示1列 */
  }

  .chart-container {
    height: 450px; /* 在超小屏幕上提供最大高度 */
  }
}
</style>